package com.lyl.security.module.login.service.impl;

import com.lyl.security.common.exception.BizException;
import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.module.login.model.dto.UserDTO;
import com.lyl.security.module.login.service.LoginService;
import com.lyl.security.module.login.service.TokenService;
import com.lyl.security.module.security.model.details.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * @author Mr.Luo
 * @date 2022-09-13 16:10
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final TokenService tokenService;

    @Override
    public String login(UserDTO dto) {
        Authentication authenticate;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            if (e instanceof BadCredentialsException) {
                throw new BizException(ErrorCode.UNAUTHORIZED, "用户名或者密码不匹配");
            } else {
                throw new BizException(ErrorCode.UNAUTHORIZED, e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return tokenService.createToken(loginUser);
    }
}
